package com.hxkj.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hxkj.domain.enums.FileExceptionEnum;
import com.hxkj.domain.enums.FileTypeJudge;
import com.hxkj.service.FileService;
import com.hxkj.utils.ImageZipUtil;
import com.hxkj.utils.JsonUtils;
import com.integral.mall.file.po.SysFile;
import com.integral.mall.file.service.SysFileService;
import com.integral.mall.file.utils.file.FileUtil;
import com.platform.common.domain.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 图片上传Client
 * <p>
 * Create by chenwei on 2018/5/23 15:19
 */
@Service
@Slf4j
@MultipartConfig(maxFileSize = -1)
public class FlieServiceImpl implements FileService {

    @Resource
    private SysFileService sysFileService;
    @Value("${cms.imgUrl}")
    private  String Path;

    @Value("${cms.path}")
    private  String Directory;

    @Value("${cms.resourcesPath}")
    private String resourcesPath;

    @Value("${cms.templetPath}")
    private String templetPath;

    @Value("${cms.fileUploadPath}")
    private String imageFilePath;

    @Value("${cms.fileUploadPath}")
    private String realPath;

    @Override
    public List<String> fileUpload(MultipartFile[] file,String filePath) throws Exception{
        try {
            //上传图片
            List<String> fileNames = getFileNames(file, filePath);
            return fileNames;
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException(FileExceptionEnum.IMAGE_UPLOAD_ERROR);
        }
    }

    @Override
    public List<String> templetUploud(MultipartFile[] file, String filePath ) throws Exception{
        try {
            //Mr.zheng:上传模板
            String fileType = "html";
            String name = "";
            List<String> fileNames = getFileNames(file, filePath);

            return fileNames;
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException(FileExceptionEnum.TEMPLET_UPLOAD_ERROR);
        }
    }


    private List<String> getFileNames(MultipartFile[] file, String filePath) {
        //获取本地临时目录
        List<String> fileNames = new ArrayList<>();
        List<String> imgLists = new ArrayList<>();
        imgLists.add("gif");
        imgLists.add("jpg");
        imgLists.add("jpeg");
        imgLists.add("bmp");
        imgLists.add("png");
        imgLists.add("psd");
        boolean flag = false;
        if(null != file && file.length > 0){
            //遍历并保存文件
            for(MultipartFile files : file){
                //获取文件名
                String fileName = files.getOriginalFilename();
                //String fiName = fileName.substring(0,fileName.lastIndexOf("."));
                String fiName = System.currentTimeMillis()+"";
                String fileType = fileName.substring(fileName.lastIndexOf(".")+1);
                if (!imgLists.contains(fileType)) {
                    flag = true;
                    break;
                }
                long size = files.getSize()/1024/1024;
                if(size >1){
                    flag = true;
                    break;
                }
                //进行sftp上传类
                SysFile sysFile = sysFileService.upload(fiName, fileType, filePath+"/" + FileUtil.getYMDPatternPath(),files);
                fileNames.add(Path + sysFile.getFilePath());
            }
            if(flag) return null;
        }
        return fileNames;
    }

    @Override
    public  List<String> appletUpload(MultipartFile [] files, String FilePath) throws Exception {
        try {
            //上传图片
            List<String> filePath = upload(files, FilePath);
            if(filePath== null){
                throw new CustomException(FileExceptionEnum.APPLET_IMG_UPLOAD_ERROR);
            }
            return filePath;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public String imgUpload(MultipartFile files, String FilePath) throws Exception {
        try {
            //上传图片
            String filePath = imgFileName(files, FilePath);
            if(filePath== null){
                throw new CustomException(FileExceptionEnum.APPLET_IMG_UPLOAD_ERROR);
            }
            return filePath;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }



    private String checkFileName(MultipartFile file, String filePath) {
        String filePaths = null;
        List<String> imgLists = new ArrayList<>();
        imgLists.add("gif");
        imgLists.add("jpg");
        imgLists.add("jpeg");
        imgLists.add("bmp");
        imgLists.add("png");
        imgLists.add("psd");
        boolean flag = false;
        if(null != file){
            //遍历并保存文件
            //获取文件名
            String fileName = file.getOriginalFilename();
            String fiName = fileName.substring(0,fileName.lastIndexOf("."));
            String fileType = fileName.substring(fileName.lastIndexOf(".")+1);
            if (!imgLists.contains(fileType)) {
                flag = true;
            }
            //进行sftp上传类
            SysFile sysFile = sysFileService.upload(fiName, fileType, filePath+"/" + FileUtil.getYMDPatternPath(),file);
            filePaths = Path + sysFile.getFilePath();

            if(flag) return null;
        }
        return filePaths;
    }


    /**
     * 小程序图片  上传
     * @param files
     * @param filePath
     * @return
     * @throws Exception
     */
    @Override
    public List<String> AppletFileUpload(MultipartFile[] files, String filePath) throws Exception {
        try {
            //上传图片
            List<String> fileNames = upload(files, filePath);
            if(fileNames== null){
                throw new CustomException(FileExceptionEnum.APPLET_IMG_UPLOAD_ERROR);
            }
            return fileNames;
        } catch (Exception e) {
            e.printStackTrace();
            throw  e;
        }
    }



    private List<String> upload(MultipartFile[] file, String filePath) {
        //获取本地临时目录
        String folder = System.getProperty("java.io.tmpdir");

        List<String> fileNames = new ArrayList<>();
        List<String> imgLists = new ArrayList<>();
        imgLists.add("gif");
        imgLists.add("jpg");
        imgLists.add("jpeg");
        imgLists.add("bmp");
        imgLists.add("png");
        imgLists.add("psd");
        boolean flag = false;
        if(null != file && file.length > 0){
            //遍历并保存文件
            for(MultipartFile files : file){
                //获取 file 绝对路径
                //获取文件名
                String fileName = files.getOriginalFilename();
                String fiName = fileName.substring(0,fileName.lastIndexOf("."));
                String fileType = fileName.substring(fileName.lastIndexOf(".")+1);
                if (!imgLists.contains(fileType)) {
                    flag = true;
                    break;
                }
                //进行sftp上传类
                try {
                    InputStream in = ImageZipUtil.zipWidthHeightImageFile(files.getInputStream(),folder,425,638,0.7f);
                    SysFile sysFile = sysFileService.upload(fiName, fileType, filePath+"/" + FileUtil.getYMDPatternPath(),in);
                    fileNames.add(Path + sysFile.getFilePath());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(flag) return null;
        }
        return fileNames;
    }

    private String imgFileName(MultipartFile file, String filePath) {
        InputStream in = null;
        //获取本地临时目录
        String folder = System.getProperty("java.io.tmpdir");
        String filePaths = null;
        List<String> imgLists = new ArrayList<>();
        imgLists.add("gif");
        imgLists.add("jpg");
        imgLists.add("jpeg");
        imgLists.add("bmp");
        imgLists.add("png");
        imgLists.add("psd");
        boolean flag = false;
        if(null != file){
            //获取文件名
            String fileName = file.getOriginalFilename();
            //String fiName = fileName.substring(0,fileName.lastIndexOf("."));
            String fiName = System.currentTimeMillis()+"";
            String fileType = fileName.substring(fileName.lastIndexOf(".")+1);
            if (!imgLists.contains(fileType)) {
                return null;
            }
            //进行sftp上传类
            try {
                long size = file.getSize()/1024;
                if(size>100){
                    in = ImageZipUtil.zipWidthHeightImageFile(file.getInputStream(),folder,320,240,10.f);
                }else {
                    in = file.getInputStream();
                }
                SysFile sysFile = sysFileService.upload(fiName, fileType, filePath+"/" + FileUtil.getYMDPatternPath(),in);
                filePaths = Path + sysFile.getFilePath();
            } catch (IOException e) {
                e.printStackTrace();
            }

            //if(flag) return null;
        }
        return filePaths;
    }


    @Override
    public JSONObject ueditorimgupload(MultipartFile file, String filePath,String action) throws Exception {
        String result  = "";
        InputStream in = null;
        //获取本地临时目录
        String folder = System.getProperty("java.io.tmpdir");
        //判断 action 是不是 congfig, 如果是就返回config.json给前端
        if (action.equals("config")){
            //File files = ResourceUtils.getFile("classpath:static/config.json");
            InputStream inputStream=this.getClass().getClassLoader().getResourceAsStream("static/config.json");
            result = JsonUtils.readFile1(inputStream);
            result.replaceAll("/\\*{1,2}[\\s\\S]*?\\*/","");
            JSONObject json = JSONObject.parseObject(result);

            return json;
        }
        Map<String, String> map  = new HashMap<>();
        try {
            //上传图片
            String filePaths = null;
            List<String> imgLists = new ArrayList<>();
            imgLists.add("gif");
            imgLists.add("jpg");
            imgLists.add("jpeg");
            imgLists.add("bmp");
            imgLists.add("png");
            imgLists.add("psd");
            boolean flag = false;
            JSONObject jsons = null;
            if (null != file) {
                //获取文件名
                String fileName = file.getOriginalFilename();
                String fiName = System.currentTimeMillis() + "";
                String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
                if (!imgLists.contains(fileType)) {
                    flag = true;
                } else {
                    //进行sftp上传类
                    long size = file.getSize()/1024;
                    if(size>100){
                        in = ImageZipUtil.zipWidthHeightImageFile(file.getInputStream(),folder,960,450,3.7f);
                    }else {
                        in = file.getInputStream();
                    }
                    SysFile sysFile = sysFileService.upload(fiName, fileType, filePath + "/" + FileUtil.getYMDPatternPath(), in);
                    filePaths = Path + sysFile.getFilePath();
                    map.put("url", filePaths);
                    map.put("state", "SUCCESS");
                    map.put("original", fiName + fileType);
                    map.put("title", fiName + fileType);
                    String mapJson = JSON.toJSONString(map);
                    jsons = JSONObject.parseObject(mapJson);
                }
                if (flag) return null;
            }
            return jsons;

        } catch (Exception e) {
            e.printStackTrace();
            throw  e;
        }

    }



    @RequestMapping(value = "/commonUpload")
    public JSONObject commonUpload(@RequestParam("file") MultipartFile  file, HttpServletRequest request) throws  Exception{
        JSONObject json = new JSONObject();
        String folder = System.getProperty("java.io.tmpdir");
        try {
            if (!file.isEmpty()) {
                String suffix = file.getOriginalFilename().substring(
                        file.getOriginalFilename().indexOf(".")+1);// 取文件格式后缀名
                String type = request.getParameter("type"); //文件上传方式
                String path = request.getParameter("path"); //文件上传路径
                String flag = request.getParameter("flag")==null?"": request.getParameter("flag");//是否压缩

                String fileName =file.getOriginalFilename();
                if (fileName.contains("\\")) {
                    fileName = StringUtils.substringAfterLast(fileName,"\\");
                }
                fileName = FilenameUtils.getBaseName(fileName);
                SysFile sysFile = null;

                /********处理模板管理图片上传*********/
                if(path.equals("ABC")){//模板查询
                    if(type.equals("1"))
                        path = templetPath+"/img";
                    else if (type.equals("2"))
                        path = templetPath+"/css";
                }else if(path.equals("BCD")){//资源查询
                    path = resourcesPath;
                    if(type.equals("1"))
                        path = resourcesPath+"/img";
                    else if (type.equals("2"))
                        path = resourcesPath+"/css";
                }else if(path.equals("CDE")){//外网文件上传
                    path = imageFilePath;
                    fileName=System.currentTimeMillis()+"";
                }

                Integer in = FileTypeJudge.getFileType(suffix.toUpperCase());
                switch (in){
                    case 1://图片上传
                        InputStream ins = file.getInputStream();
                        if(flag.equals("1"))
                            ins = ImageZipUtil.zipWidthHeightImageFile(ins ,folder,320,240,10.f);
                        sysFile = sysFileService.upload(fileName, suffix, path,file);
                        break;
                    case 2: //文档上传
                        ins = file.getInputStream();
                        sysFile = sysFileService.upload(fileName, suffix, path,ins);
                        break;
                    case 3 :   //视频上传
                        sysFile = sysFileService.upload(fileName, suffix, path+"/" + FileUtil.getYMDPatternPath(),file.getInputStream());
                        break;
                    case 4://种子上传
                        sysFile = sysFileService.upload(fileName, suffix, path+"/" + FileUtil.getYMDPatternPath(),file.getInputStream());
                        break;
                    case 5://音乐上传
                        sysFile = sysFileService.upload(fileName, suffix, path+"/" + FileUtil.getYMDPatternPath(),file.getInputStream());
                        break;
                    case 7://其它上传(不支持文件上传)
                        throw new CustomException(FileExceptionEnum.FILE_NONE_SUPPORT_UPLOAD);
                }
                if(sysFile != null)json.put("path","/"+Path+sysFile.getFilePath());
            }else{
                throw new CustomException(FileExceptionEnum.PLEASE_FILE_UPLOAD);
            }
        }catch(Exception e){
            e.printStackTrace();
            throw e;
        }
        return json;
    }


}
